<script setup>
import { ref, computed } from 'vue'
import Item from './Item.vue'
import Tabs from './Tabs.vue'
import { todosStore } from '../store/todos.js'
import { storeToRefs } from 'pinia'
const todosstore = todosStore()
const { todos } = storeToRefs(todosstore)
const todoid = ref(0)
// const todos = ref([])
const filter = ref('all')

const addTodo = (event) => {
    const content = event.target.value.trim();
    if (content) {
        todos.value.push({
            id: todoid.value++,
            content: content,
            completed: false
        });
        event.target.value = ''
        changeArrFun('all');
    } else {
        alert('输入不能为空');
    }
}

const delItem = (i) => {
    const del_id = todos.value.findIndex(todo => todo.id === i)
    todos.value.splice(del_id, 1)
}

const toggleState = (state) => {
    filter.value = state
}

const clearCompleted = () => {
    // filteredTodos.value = []
    todos.value = []
}

// const changeArrFun = (state) => {
//     if (state === 'active') {
//         filteredTodos.value = todos.value.filter(todo => !todo.completed);
//     } else if (state === 'completed') {
//         filteredTodos.value = todos.value.filter(todo => todo.completed);
//     } else if (state === 'all') {
//         filteredTodos.value = todos.value;
//     }
// }
const changeArrayComputed = computed(() => {
    if (filter.value == 'all') {
        return todos.value
    } else if (filter.value == 'active') {
        return todos.value.filter((todo) => !todo.completed)
    } else if (filter.value == 'completed') {
        return todos.value.filter((todo) => todo.completed)
    }
})
const changeCompleted = (i) => {
    const change_id = todos.value.findIndex(todo => todo.id === i)
    todos.value[change_id].completed = !todos.value[change_id].completed
}
</script>

<template>
    <div id="todo">
        <input type="text" placeholder="接下来做什么？" @keyup.enter="addTodo">
        <div id="items">
            <item v-for="todo in changeArrayComputed" :key="todo.id" :todo="todo" @del="delItem"
                @changecompleted="changeCompleted">
            </item>
        </div>
        <tabs :todos="changeArrayComputed" :filter="filter" @toggle="toggleState" @changearray="changeArrFun"
            @clear="clearCompleted">
        </tabs>
    </div>
</template>

<style scoped>
#todo {
    position: relative;
    width: 560px;
    height: 300px;
    padding: 20px;
    background: #ffffff;
    margin: 0 auto;
}

input {
    font-size: 30px;
    outline: none;
    border: none;
}

#items {
    height: 240px;
}
</style>
